package com.jetpack_sunflower.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.jetpack_sunflower.PlantListFragmentDirections
import com.jetpack_sunflower.data.Plant
import com.jetpack_sunflower.databinding.LayoutItemPlantBinding

class PlantAdapter() : ListAdapter<Plant, PlantAdapter.ViewHolder>(PlantDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val binding = LayoutItemPlantBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)
        holder.apply {
            bind(createOnViewClickListener(item.plantId), item)
            itemView.tag = item
        }
    }

    private fun createOnViewClickListener(plantId: String): View.OnClickListener {
        return View.OnClickListener {
            val direction = PlantListFragmentDirections.actionPlantListFragmentToPlantDetailFragment(plantId)
            it.findNavController().navigate(direction)
        }
    }

    class ViewHolder(private val binding: LayoutItemPlantBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(listener: View.OnClickListener, item: Plant) {
            binding.apply {
                plant = item
                clickListener = listener
                executePendingBindings()
            }
        }
    }
}